package com.weiqiao.report.distributior.Service.impl;

import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.mongodb.client.model.Filters;
import com.weiqiao.mall.domain.AccountDetailEntity;
import com.weiqiao.mall.repository.IAccountDetaiRepository;
import com.weiqiao.report.distributior.Service.DistributiorService;
import com.weiqiao.report.util.DateUtil;
import com.weiqiao.report.util.RequestCheckUtil;
import com.weiqiao.report.util.Tool;
import com.weiqiao.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@Slf4j
@Service("DistributiorServiceImpl")
public class DistributiorServiceImpl implements DistributiorService {

    @Autowired
    private IAccountDetaiRepository accountDetaiRepository;

    @Override
    public ResponseEntity exportAccountedDetailList(HttpServletRequest request, HttpServletResponse response) {
        RequestCheckUtil.checkCompanyid(request);
        int company_id = Integer.valueOf(request.getParameter("company_id"));
        Bson filter = Filters.eq("delete_flag", 0);
        filter = this.getAccountedDetailQueryParamter(request, filter);
        int pageSize = accountDetaiRepository.countNum(company_id, filter) + 1;
        int pageNo = 0;
        Bson sort = Filters.eq("create_time", -1);
        List<AccountDetailEntity> account_detail_list =
                queryAccountDetail(filter, company_id, sort, pageNo, pageSize);
        if (CollectionUtils.isEmpty(account_detail_list)) {
            return new ResponseEntity(HttpStatus.NO_CONTENT);
        }
        // 创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();
        // 建立新的sheet对象（excel的表单）
        HSSFSheet sheet = wb.createSheet("收支明细表");
        // 在sheet sheet1里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
        HSSFRow row1 = sheet.createRow(0);
        // 创建单元格并设置单元格内容 sheet>>>row1 按产品导出
        row1.createCell(0).setCellValue("客户编号");
        row1.createCell(1).setCellValue("手机号码");
        row1.createCell(2).setCellValue("微信昵称");
        row1.createCell(3).setCellValue("订单编号");
        row1.createCell(4).setCellValue("交易编号");
        row1.createCell(5).setCellValue("收支类型");
        row1.createCell(6).setCellValue("退回返利金额");
        row1.createCell(7).setCellValue("金额");
        row1.createCell(8).setCellValue("收支状态");
        row1.createCell(9).setCellValue("结算时间");
        row1.createCell(10).setCellValue("创建时间");


        int num = 0;

        for (AccountDetailEntity entity : account_detail_list) {
            String happen_proceed = Tool.getHappenProceed(entity.getHappen_proceed());
            String result_type = Tool.getResultType(entity.getResult_type());
            num++;
            HSSFRow row2 = sheet.createRow(num);

            row2.createCell(0).setCellValue(entity.getUser_id());
            row2.createCell(1).setCellValue(entity.getPhone());
            row2.createCell(2).setCellValue(entity.getName());
            row2.createCell(3).setCellValue(entity.getOrder_no());
            row2.createCell(4).setCellValue(entity.getAccount_no());
            row2.createCell(5).setCellValue(happen_proceed);
            row2.createCell(6).setCellValue(entity.getReturn_rebate());
            row2.createCell(7).setCellValue(entity.getAccount_money());
            row2.createCell(8).setCellValue(result_type);
            row2.createCell(9).setCellValue(entity.getDeal_time());
            row2.createCell(10).setCellValue(entity.getCreat_time());

        }
        Tool.exportFinal(response, wb);
        return new ResponseEntity(HttpStatus.OK);
    }

    @Override
    public Bson getAccountedDetailQueryParamter(HttpServletRequest request, Bson filter) {
        // 前端参数
        String customer_type = request.getParameter("customer_type");
        String user_id = request.getParameter("user_id");
        String account_no = request.getParameter("account_no");
        String happen_proceed = request.getParameter("happen_proceed");
        String phone = request.getParameter("phone");
        String custom_id = request.getParameter("custom_id");
        String order_no = request.getParameter("order_no");
        // 统计结束时间
        String deal_time = request.getParameter("deal_time");
        // 创建时间
        String creat_time = request.getParameter("creat_time");
        String account_no_list = request.getParameter("account_no_list");
        String result_type = request.getParameter("result_type");
        List<String> account_nolist = new ArrayList<>();
        if (account_no_list != null && account_no_list.split(",").length > 0) {
            String[] split = account_no_list.split(",");
            for (int i = 0; i < split.length; i++) {
                if (StringUtils.isNumeric(split[i])) {
                    account_nolist.add(split[i]);
                }
            }
            filter = Filters.and(filter, Filters.in("account_no", account_nolist));
        }
        // 关键词(根据手机号或微信昵称模糊搜索)
        if (StringUtil.isInteger(user_id)) {
            filter = Filters.and(filter, Filters.eq("user_id", Integer.parseInt(user_id)));
        }
        if (!StringUtil.isBlank(creat_time)) {
            filter = Filters.and(filter, Filters.gte("creat_time", "" + DateUtil.getTime(creat_time.split("~")[0])),
                    Filters.lte("creat_time", "" + DateUtil.getTime(creat_time.split("~")[1])));
        }
        if (!StringUtil.isBlank(account_no)) {
            filter = Filters.and(filter, Filters.eq("account_no", account_no));
        }
        if (StringUtil.isInteger(happen_proceed)) {
            filter = Filters.and(filter, Filters.eq("happen_proceed", Integer.parseInt(happen_proceed)));
        }
        if (StringUtil.isInteger(custom_id)) {
            filter = Filters.and(filter, Filters.eq("custom_id", Integer.parseInt(custom_id)));
        }
        if (StringUtil.isInteger(customer_type)) {
            filter = Filters.and(filter, Filters.eq("customer_type", Integer.parseInt(customer_type)));
        }
        if (!StringUtil.isBlank(deal_time) && deal_time.split("~").length > 1) {
            filter = DateUtil.getTimeQuery(deal_time, filter, "deal_time");
        }
        if (!StringUtil.isBlank(phone)) {
            Pattern pattern = Pattern.compile("^.*" + phone + ".*$", Pattern.CASE_INSENSITIVE);
            filter = Filters.and(filter, Filters.eq("phone", pattern));
        }
        if (StringUtil.isInteger(result_type)) {
            filter = Filters.and(filter, Filters.eq("result_type", Integer.parseInt(result_type)));
        }
        if (!StringUtil.isBlank(order_no)) {
            filter = Filters.and(filter, Filters.eq("order_no", order_no));
        }
        return filter;
    }

    private List<AccountDetailEntity> queryAccountDetail(Bson filter, int company_id, Bson sort, int pageNo, int pageSize) {
        List<AccountDetailEntity> accountDetailEntityList = new ArrayList<>();
        int skip = pageNo * pageSize;
        List<String> detailStrs = accountDetaiRepository.getAccountDetailByFilterSortLimit(company_id, filter, sort, skip, pageSize);
        if (detailStrs != null && detailStrs.size() > 0) {
            for (String detailStr : detailStrs) {
                AccountDetailEntity entity = new Gson().fromJson(detailStr, AccountDetailEntity.class);
                if (!StringUtil.isBlank(entity.getCreat_time())) {
                    entity.setCreat_time(DateUtil.timestampToString(entity.getCreat_time()));
                }
                if (!StringUtil.isBlank(entity.getDeal_time())) {
                    entity.setDeal_time(DateUtil.timestampToString(entity.getDeal_time()));
                }
                entity.setNickname(entity.getName());
                accountDetailEntityList.add(entity);
            }
        }
        return accountDetailEntityList;
    }

    @Override
    public ResponseEntity exportDistributiorStatistics(HttpServletRequest request, HttpServletResponse response) {
        return new ResponseEntity(HttpStatus.OK);
    }


    @Override
    public ResponseEntity exportRebaterList(HttpServletRequest request, HttpServletResponse response) {
        return new ResponseEntity(HttpStatus.OK);
    }

}
